<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 闪现付
 */
class ShanxianfuController extends PayController{
    protected $config;
    protected $class;
    private $merchant_private_key;
    private $merchant_public_key;
    private $web_public_key;

    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));


        $this->merchant_private_key = file_get_contents("Files/".$this->class."/merchant_private_key.txt");
        $this->merchant_public_key = file_get_contents("Files/".$this->class."/merchant_public_key.txt");
        $this->web_public_key = file_get_contents("Files/".$this->class."/web_public_key.txt");
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['version'] = 'V3.0.0.0';
        $data['merchNo'] = $this->config['mch_id'];

        switch($this->config['paytype']) {
            //微信
            case 1:
                $data['netwayCode'] = 'PS_QM';
                break;
            //支付宝
            case 3:
                $data['netwayCode'] = 'PS_BANK';
                break;
            //支付宝H5
            case 4:
                $data['netwayCode'] = 'PS_BANK';
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $data['randomNum'] = substr(md5(date("YmdHis".mt_rand(10000,99999))), 0, 8);
        $data['orderNum'] = $return['orderid'];
        $data['amount'] = strval(intval($return['amount']*100));
        $data['goodsName'] = 'zf';
        $data['callBackUrl'] = $return['notifyurl'];
        $data['callBackViewUrl'] = $return['callbackurl'];
        $data['charset'] = 'UTF-8';

        ksort($data);

        $str = str_replace("\\","",json_encode($data).$this->config['signkey']);
        $data['sign'] = strtoupper(md5($str));

        ksort($data);

        $json = json_encode($data,320);

        $dataStr = $this->encode_pay($json);

        $param = 'data=' . urlencode($dataStr) . '&merchNo=' . $this->config['mch_id'] . '&version=V3.0.0.0';
        $result = curl($this->config['gateway'],$param);

        $res = json_decode($result, true);

        $code = $res['qrcodeUrl'];
        if(!$code){
            if($res['msg']){
                $this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location: {$code}");
    }

    private function encode_pay($data){
        $pu_key = openssl_pkey_get_public($this->merchant_public_key);
        $encryptData = '';
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pu_key);
            $crypto = $crypto . $encryptData;
        }

        $crypto = base64_encode($crypto);
        return $crypto;
    }

    function rsa_decrypt($encrypted, $rsa_private_key){
        $crypto = '';
        $encrypted = base64_decode($encrypted);
        foreach (str_split($encrypted, 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $rsa_private_key);
            $crypto .= $decryptData;
        }
        return $crypto;
    }

    //通知
    public function notifyurl(){
        exit();
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export(I("post."),true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

		//$this->debug_callback();

        if(!$this->checkip(getIP(),['43.243.93.89'])){
            exit("wrong");
        }

        $p = I("post.");

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['orderNum'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
      /*  M("Order")->where(array("pay_orderid"=>$orderid))->save(array(


        ));*/

        //获取渠道信息
        $this->config = Channel::getInstance()->getById($find['channel_id']);

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);

        $str = '';
        foreach($p as $k=>$v){
            if($v === ""){
                continue;
            }
            $str .= $v;
        }
        $str .= $this->config['signkey'];
        $sign2 = md5($str);

        $notify = $p['data'];
        $mer_private_key = openssl_pkey_get_private($this->merchant_private_key);
        $data = $this->rsa_decrypt($notify, $mer_private_key);//执行解密流程
        $context_arr = json_decode($data, true);//转为数组格式

        if(!$context_arr){
            echo "no_rights"; exit;
        }

        $sign = $context_arr['sign'];
        unset($context_arr['sign']);
        ksort($context_arr);

        $str = str_replace("\\","",json_encode($context_arr).$this->config['signkey']);
        $sign2 = strtoupper(md5($str));

        if($sign !== $sign2){
            echo 'sign_wrong';exit;
        }

        if($context_arr['payStateCode'] !== '00'){
            echo "pay_fail";exit;
        }
        /*
         * Array
        (
            [amount] => 5000
            [goodsName] => zf
            [merchNo] => SH201811090003
            [netwayCode] => PS_ZFB
            [orderNum] => 2018112221312129650
            [payDate] => 20181122213144
            [payStateCode] => 00
            [sign] => 4C14006F0452293730D606D860AB9C2A
        )
         */

        //回调成功
        $this->async($find['pay_orderid'],"SUCCESS");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}